namespace("lesp.application");

/**
 * Main interface renderer.
 */
lesp.application.Renderer = Base.extend({

  constructor : function()
  {
    if(!jQuery(".track-detail .wiki").length)
    {
      jQuery(".track-detail")
        .append("<h2 class='heading'><span class='h2Wrapper'>About This Track</span></h2>")
        .append("<div class='wiki'></div>");
    }
  },

  add : function(renderer)
  {
    var progress = document.createElement('img');
    progress.id  = new Date().valueOf();
    progress.src = GM_getResourceURL("progress");

    var container = jQuery("<div style='margin-top: 15px;'/>")
      .append("<h3 style='color: #D51007;'>{0}</h3>".format(renderer.getTitle()))
      .append(progress)
      .appendTo(".track-detail .wiki");

    renderer.attach("completed", function()
    {
      container.find("#" + progress.id).remove();
      container.append(renderer.render());
    });
    renderer.attach("failed", function()
    {
      container.find("#" + progress.id).remove();
      container.append("Not found");
    });
  }

});

/**
 * Main manager.
 */
lesp.application.Application = Base.extend({

  _artist   : null,
  _track    : null,
  _renderer : null,


  constructor : function()
  {
    if(!unsafeWindow.LFM || !unsafeWindow.LFM.get("ParentResource"))
    {
      throw new Error("Invalid last.fm page");
    }

    var resource = unsafeWindow.LFM.get("ParentResource");
    if(resource.type != 9)
    {
      throw new Error("This isn't a track page");
    }
    
    this._artist = resource.artistname;
    this._track  = resource.name;

    this._renderer = new lesp.application.Renderer();
  },

  main : function()
  {
    var renderers = [
      new lesp.songfacts.Renderer(new lesp.songfacts.Manager(this._artist, this._track)),
      new lesp.songmeanings.Renderer(new lesp.songmeanings.Manager(this._artist, this._track))
    ];
    renderers.forEach(this._renderer.add, this._renderer);
    
    // purpose:
    //   * debug exclude regex
    //   * look at usage 
    unsafeWindow._gat && unsafeWindow._gat._getTracker("UA-29858354-3")._trackPageview();
  }

});


